package com.hospital.controller;

import com.hospital.dao.DoctorViewDao;
import com.hospital.dao.impl.DoctorViewDaoImpl;
import com.hospital.model.DoctorView;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
/**
 * 处理医生登录请求，验证医生ID和密码，并重定向到医生主页
 */
@WebServlet("/doctorLogin")
public class DoctorLoginServlet extends HttpServlet {
    /** 医生视图数据访问对象，用于处理医生登录验证和信息查询 */
    private DoctorViewDao doctorViewDao;
    
    @Override
    public void init() throws ServletException {
        doctorViewDao = new DoctorViewDaoImpl();
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        String doctorId = request.getParameter("doctorId");
        String password = request.getParameter("password");
        
        try {
            DoctorView doctor = doctorViewDao.validateLogin(doctorId, password);
            
            if (doctor != null) {
                // 登录成功
                HttpSession session = request.getSession();
                session.setAttribute("doctor", doctor);
                response.sendRedirect("dashboard.jsp");
            } else {
                // 登录失败
                request.setAttribute("error", "工号或密码错误");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            // 数据库错误
            request.setAttribute("error", "系统错误，请稍后重试");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            e.printStackTrace();
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.sendRedirect("login.jsp");
    }
} 